package com.awesome.network.request;

import com.awesome.network.callback.OnProgressListener;

import java.io.File;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.internal.Util;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

/**
 * Author: JFangZ
 * Email:janezhang1901@163.com
 * Date: 2020/7/2 15:44
 * Description:上传文件时的代理 RequestBody,在这里面可以回调上传进度
 */
public class UploadRequestBody extends RequestBody {

    public static final int SEGMENT_SIZE = 1024 * 8;

    private final File mFile;
    private final String mContentType;
    private final OnProgressListener mListener;

    public UploadRequestBody(File file, String contentType, OnProgressListener listener) {
        mFile = file;
        mContentType = contentType;
        mListener = listener;
    }

    @Override
    public long contentLength() {
        return mFile.length();
    }

    @Override
    public MediaType contentType() {
        return MediaType.parse(mContentType);
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        Source source = null;
        try {
            source = Okio.source(mFile);
            long currentLength = 0;
            long len;

            while ((len = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
                currentLength += len;
                sink.flush();
                if (mListener != null) {
                    mListener.onProgress(currentLength, contentLength());
                }
            }
        } finally {
            Util.closeQuietly(source);
        }
    }
}